<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Updater</title>
    <link rel="stylesheet" href="resources/updater.css" />
    <link rel="stylesheet" href="resources/bootstrap-progressbar/css/bootstrap-progressbar-3.3.0.min.css">
    <link rel="stylesheet" href="resources/style.css" />

    <script src="resources/jquery-2.1.3.min.js"></script>
    <script src="resources/bootstrap-progressbar/bootstrap-progressbar.min.js"></script>
</head>

<body>
    <div class="spinner">
      <div class="dot1"></div>
      <div class="dot2"></div>
    </div>
    <center style="z-index: 2">
    	<div id="starter" style="display:none">
            <h2 id="update-header" style="margin-bottom: 5px">Update to Powder</h2>
            <div id="donwload-now" onClick="startDownload()" class="actionButton droid-bold">Download Now!</div>
            <div id="maybe-later" onClick="win.close()" class="actionButton droid-bold">Maybe Later ...</div>
        </div>
		<div id="downloader" style="display:none; padding:30px 15px; background:#5AA5C9; color: #fff">
            <div class="droid-bold">Downloading ...</div>
            <div id="all-download" class="progress" style="margin:10px 0; width: 100%">
                <div class="progress-bar progress-bar-warning" role="progressbar" data-transitiongoal="0" style="transition: width .0s ease"></div>
            </div>
            <div class="stats">
                <span>Progress: <span id="downPart">0 kB</span> / <span id="downAll">0 kB</span></span>
            </div>
        </div>
    	<div id="ender" style="display:none">
            <h2 id="update-header" style="font-size:15px">Downloaded Successfully</h2>
			<i style="font-size:13px; display:inline-block; padding:10px 30px; background:#5AA5C9; color:#fff; margin-bottom:2px">Powder Player will be closed during the updating process.</i>
            <div id="donwload-now" onClick="runUpdate()" class="actionButton droid-bold">Run Update Now!</div>
        </div>
    </center>
    
	<script>
	localStorage.doUpdate = "0";
	
	var isWin = /^win/.test(process.platform);
	
	if (isWin) {
		var pathBreak = "\\",
			appExt = ".exe";
	} else {
		var pathBreak = "/";
		if (process.platform == "darwin") var appExt = ".dmg";
		else if (process.platform == "linux") var appExt = ".tar.gz";
	}
	
	var request = require('request'),
		gui = require('nw.gui'),
		fs = require('fs'),
		file_url;
	
	var https = require('https');
	
	var options = {
		host: 'api.github.com',
		path: '/repos/jaruba/PowderPlayer/releases',
		method: 'GET',
		headers: {'user-agent': 'node.js'}
	};
	
	var apiRequest = https.request(options, function(response) {
		var body = '';
		response.on("data", function(chunk) {
			body += chunk.toString('utf8');
		});
		
		response.on("end", function() {
			jsonData = JSON.parse(body);
			for (mn = 0; jsonData[mn]; mn++) {
				for (kl = 0; jsonData[mn]["assets"][kl]; kl++) {
					if (jsonData[mn]["assets"][kl]["browser_download_url"].split(".").pop() == appExt.split(".").pop()) {
						file_url = jsonData[mn]["assets"][kl]["browser_download_url"];
						$("#update-header").text("Update to Powder "+jsonData[mn]["tag_name"]);
						$(".spinner").fadeOut();
						$("#starter").fadeIn();
						return;
					}
				}
			}
			if (!file_url) win.close();
		});
	});
	
	apiRequest.end();
		
	gui.Screen.Init();
	
	var win = gui.Window.get();
	win.setMaximumSize(320,133);
	win.setMinimumSize(320,133);
	win.resizeTo(320,133);
	win.setResizable(false);
	
	var total = 0;
	var current = 0;
	
	var focused = true;
	win.focus();
	win.on('focus', function() { focused = true; }); 
	win.on('blur', function() { focused = false; });
		
	function getReadableFileSizeString(fileSizeInBytes) {
		var i = -1;
		var byteUnits = [' kB', ' MB', ' GB', ' TB', 'PB', 'EB', 'ZB', 'YB'];
		do {
			fileSizeInBytes = fileSizeInBytes / 1024;
			i++;
		} while (fileSizeInBytes > 1024);
		return Math.max(fileSizeInBytes, 0.1).toFixed(1) + byteUnits[i];
	}
	
	function startDownload() {
		var out = fs.createWriteStream(gui.App.dataPath+pathBreak+'updater'+appExt);
		
		$("#starter").css("display","none");
		$("#downloader").css("display","block");
		
		var req = request({
			method: 'GET',
			uri: file_url
		});
		req.pipe(out);
		
		req.on('data', function (chunk) {
			current += chunk.length;
			$("#downPart").text(getReadableFileSizeString(current));
			$('#all-download .progress-bar').attr('data-transitiongoal', ((current/total)*100)).progressbar({display_text: 'center'});
		});
		
		req.on('response', function (data) {
			total = data.headers['content-length'];
			$("#downAll").text(getReadableFileSizeString(total));
		});
		
		req.on('end', function() {
			$("#downloader").css("display","none");
			$("#ender").css("display","block");
			if (!focused) win.requestAttention(true);
		});
	}
	function runUpdate() {
		localStorage.doUpdate = "1";
		gui.Shell.openExternal(gui.App.dataPath+pathBreak+'updater'+appExt);
		win.close();
	}
    </script>
</body>
</html>
